﻿using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Web;
using System.Text.RegularExpressions;
using LitJson;
using ShareMarking.Systems.Entity;
using ShareMarking.Systems.Service;
using ShareMarking.Services;
using System.Net;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Drawing.Imaging;

namespace DTcms.Web.tools
{
    /// <summary>
    /// 文件上传处理页
    /// </summary>
    public class upload_ajax : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = DTRequest.GetQueryString("action");

            switch (action)
            {
                case "EditorFile": //编辑器文件
                    EditorFile(context);
                    break;
                case "ManagerFile": //管理文件
                    ManagerFile(context);
                    break;
                case "BuildZip": //打包zip文件
                    BuildZip(context);
                    break;
                case "DownloadZip": //打包zip文件
                    DownloadZip(context);
                    break;
                default: //普通上传
                    UpLoadFile(context); 
                    break;
            }

        }

        #region 上传文件处理===================================
        private void UpLoadFile(HttpContext context)
        {
            string _delfile = DTRequest.GetString("DelFilePath");
            HttpPostedFile _upfile = context.Request.Files["Filedata"];
            bool _iswater = false; //默认不打水印
            bool _isthumbnail = false; //默认不生成缩略图

            if (DTRequest.GetQueryString("IsWater") == "1")
                _iswater = true;
            if (DTRequest.GetQueryString("IsThumbnail") == "1")
                _isthumbnail = true;
            if (_upfile == null)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件！\"}");
                return; 
            }
            UpLoad upFiles = new UpLoad();
            string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater);
            //删除已存在的旧文件
            //if (!string.IsNullOrEmpty(_delfile))
            //{
            //    Utils.DeleteUpFile(_delfile);
            //}
            //返回成功信息
            context.Response.Write(msg);
            context.Response.End();
        }
        #endregion

        #region 编辑器上传处理===================================
        private void EditorFile(HttpContext context)
        {
            bool _iswater = false; //默认不打水印
            if (context.Request.QueryString["IsWater"] == "1")
                _iswater = true;
            HttpPostedFile imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                showError(context, "请选择要上传文件！");
                return;
            }
            UpLoad upFiles = new UpLoad();
            
            string remsg = upFiles.fileSaveAs(imgFile, false, _iswater);
            JsonData jd = JsonMapper.ToObject(remsg);
            string status = jd["status"].ToString();
            string msg = jd["msg"].ToString();
            if (status == "0")
            {
                showError(context, msg);
                return;
            }
            string filePath = jd["path"].ToString(); //取得上传后的路径
            Hashtable hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = filePath;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }
        //显示错误
        private void showError(HttpContext context, string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }
        #endregion

        #region 浏览文件处理=====================================
        private void ManagerFile(HttpContext context)
        {
            siteconfig siteConfig = siteconfigService.Instance.loadConfig();
            //String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            //根目录路径，相对路径
            String rootPath = siteConfig.webpath + siteConfig.filepath + "/"; //站点目录+上传目录
            //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
            String rootUrl = siteConfig.webpath + siteConfig.filepath + "/";
            //图片扩展名
            String fileTypes = "gif,jpg,jpeg,png,bmp";

            String currentPath = "";
            String currentUrl = "";
            String currentDirPath = "";
            String moveupDirPath = "";

            String dirPath = Utils.GetMapPath(rootPath);
            String dirName = context.Request.QueryString["dir"];

            //根据path参数，设置各路径和URL
            String path = context.Request.QueryString["path"];
            path = String.IsNullOrEmpty(path) ? "" : path;
            if (path == "")
            {
                currentPath = dirPath;
                currentUrl = rootUrl;
                currentDirPath = "";
                moveupDirPath = "";
            }
            else
            {
                currentPath = dirPath + path;
                currentUrl = rootUrl + path;
                currentDirPath = path;
                moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
            }

            //排序形式，name or size or type
            String order = context.Request.QueryString["order"];
            order = String.IsNullOrEmpty(order) ? "" : order.ToLower();

            //不允许使用..移动到上一级目录
            if (Regex.IsMatch(path, @"\.\."))
            {
                context.Response.Write("Access is not allowed.");
                context.Response.End();
            }
            //最后一个字符不是/
            if (path != "" && !path.EndsWith("/"))
            {
                context.Response.Write("Parameter is not valid.");
                context.Response.End();
            }
            //目录不存在或不是目录
            if (!Directory.Exists(currentPath))
            {
                context.Response.Write("Directory does not exist.");
                context.Response.End();
            }

            //遍历目录取得文件信息
            string[] dirList = Directory.GetDirectories(currentPath);
            string[] fileList = Directory.GetFiles(currentPath);

            switch (order)
            {
                case "size":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new SizeSorter());
                    break;
                case "type":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new TypeSorter());
                    break;
                case "name":
                default:
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new NameSorter());
                    break;
            }

            Hashtable result = new Hashtable();
            result["moveup_dir_path"] = moveupDirPath;
            result["current_dir_path"] = currentDirPath;
            result["current_url"] = currentUrl;
            result["total_count"] = dirList.Length + fileList.Length;
            List<Hashtable> dirFileList = new List<Hashtable>();
            result["file_list"] = dirFileList;
            for (int i = 0; i < dirList.Length; i++)
            {
                DirectoryInfo dir = new DirectoryInfo(dirList[i]);
                Hashtable hash = new Hashtable();
                hash["is_dir"] = true;
                hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
                hash["filesize"] = 0;
                hash["is_photo"] = false;
                hash["filetype"] = "";
                hash["filename"] = dir.Name;
                hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                dirFileList.Add(hash);
            }
            for (int i = 0; i < fileList.Length; i++)
            {
                FileInfo file = new FileInfo(fileList[i]);
                Hashtable hash = new Hashtable();
                hash["is_dir"] = false;
                hash["has_file"] = false;
                hash["filesize"] = file.Length;
                hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
                hash["filetype"] = file.Extension.Substring(1);
                hash["filename"] = file.Name;
                hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                dirFileList.Add(hash);
            }
            context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(result));
            context.Response.End();
        }

        #region Helper
        public class NameSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.FullName.CompareTo(yInfo.FullName);
            }
        }

        public class SizeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Length.CompareTo(yInfo.Length);
            }
        }

        public class TypeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Extension.CompareTo(yInfo.Extension);
            }
        }
        #endregion
        #endregion

        #region 生成Zip=====================================
        private void BuildZip(HttpContext context)
        {
            #region 初始化变量
            string info = "";
            int SuccessCount = 0;
            int ErroCount = 0;
            WebClient my = new WebClient();
            int HttpCode = 0;
            #endregion

            #region 查询门店图片列表
            //var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.StoreCode == "20269405" || qr_Store._.StoreCode == "20607840", null);
            var nclist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupload == true, qr_Store._.id.Asc);
            ComLib.LogLib.Log4NetBase.Log("1、---------------导出门店图片开始,总共::" + nclist.Count + "条数据---------------");


            if (nclist.Count > 0)
            {
                string virtulPath = "/upload/storeimg/" + DateTime.Now.ToString("yyyyMMddHHmmss");
                var path = System.Web.HttpContext.Current.Request.MapPath(virtulPath + "/");
                //path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
                //1.检查保存的物理路径是否存在，不存在则创建
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //2.Zip打包路径 
                string zipPath = Utils.GetMapPath(virtulPath);

                //3.保存图片
                #region 循环遍历保存图片
                for (int i = 0; i < nclist.Count; i++)
                {
                    var o = nclist[i];
                    bool result = false;
                    ComLib.LogLib.Log4NetBase.Log("2、---------------正在执行第(" + i + ")条数据---------------");
                    #region 查询关联表qr_Type == 1002
                    var entity = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                        qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                        && qr_QrCodeRelate._.rel_Code == o.StoreCode);
                    #endregion

                    if (entity != null)
                    {
                        #region 查询微信url，保存图片进文件夹
                        info = "门店ID:" + o.StoreCode + "//门店名称:" + o.S_Name;
                        var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == entity.qr_CodeID);
                        if (qrcode != null)
                        {
                            #region 检验URL是否可访问
                            HttpCode = zip_http.GetStatusCode(qrcode.qrcode_url);
                            if (HttpCode == 200)
                            {
                                byte[] mybyte;
                                mybyte = my.DownloadData(qrcode.qrcode_url);
                                MemoryStream ms = new MemoryStream(mybyte);
                                System.Drawing.Image img;
                                img = System.Drawing.Image.FromStream(ms);
                                string newFileName = path + o.StoreCode + "-" + o.S_Name.Replace("?", "").Replace("？", "").Replace("<", "").Replace(">", "").Replace(":", "").Replace("*", "") + ".png"; //文件名
                                string newpath = newFileName.ToString().Trim();
                                img.Save(newpath, ImageFormat.Png);   //保存
                                o.isneedupload = false;
                                result = qr_StoreService.Instance.Update_Entity(o);
                            }
                            else
                            {
                                result = false;
                                //ErroCount += 1;//不可访问也失败
                            }
                            #endregion
                        }
                        else
                        {
                            result = false;
                            //ErroCount += 1;//qr_DiyCode没有记录也失败
                            ComLib.LogLib.Log4NetBase.Log("0-0、---------------导出门店图片失败::qr_DiyCode没有记录" + info + "---------------");
                        }
                        if (result == true)
                        {
                            SuccessCount += 1;
                            ComLib.LogLib.Log4NetBase.Log("3、---------------导出门店图片成功::" + info + "---------------");
                        }
                        else
                        {
                            ErroCount += 1;
                            ComLib.LogLib.Log4NetBase.Log("3、---------------导出门店图片失败::" + info + "---------------");
                        }
                        #endregion
                    }
                    else
                    {
                        ErroCount += 1;//qr_QrCodeRelate没关联记录也失败
                        ComLib.LogLib.Log4NetBase.Log("0-0、---------------导出门店图片失败::qr_QrCodeRelate没关联记录;门店ID:" + o.StoreCode + "---------------");
                    }
                }
                #endregion                
              
                Hashtable hash = new Hashtable();
                hash["error"] = 0;
                hash["message"] = "打包二维码图片成功！";
                hash["path"] = path;
                hash["zipPath"] = zipPath;
                hash["virtulPath"] = virtulPath+".zip";

                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                context.Response.Write(JsonMapper.ToJson(hash));
                context.Response.End();
            }
            else
            {               
               showError(context, "暂无二维码图片导出，请先导入门店！");
               return;               
            }

            #endregion
        }
        #endregion

        #region 下载Zip=====================================
        private void DownloadZip(HttpContext context)
        {
            string folderPath = DTRequest.GetString("path");//保存的文件路径
            string zipFilePath = DTRequest.GetString("zipPath");//zip文件名称
            if (folderPath == "" || zipFilePath == "")
            {
                showError(context, "请先生成zip包，再点击下载！");
            }
            else
            {
                //4.打包图片成zip文件
                #region 片成zip文件
                zip_http.ZipFolderContents(folderPath, zipFilePath + ".zip");
                ComLib.LogLib.Log4NetBase.Log("1、---------------下载门店图片zip结束！时间:" + DateTime.Now + ",路径:" + zipFilePath + "---------------");
                //JscriptMsg("导出门店图片结束！成功" + SuccessCount + "条；失败" + ErroCount + "条---------------", "Index.aspx", "Success");
                #endregion

                //5、通知浏览器下载文件而不是打开  
                #region 浏览器下载文件
                ////以字符流的形式下载文件  
                //FileStream fs = new FileStream(zipFilePath + ".zip", FileMode.Open);
                //byte[] bytes = new byte[(int)fs.Length];
                //fs.Read(bytes, 0, bytes.Length);
                //fs.Close();
                
                //context.ApplicationInstance.Response.ContentType = "application/octet-stream";
                //context.ApplicationInstance.Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMdd") + "门店二维码图片.zip", System.Text.Encoding.UTF8));
                //context.ApplicationInstance.Response.BinaryWrite(bytes);
                //context.ApplicationInstance.Response.Write(JsonMapper.ToJson(hash));
                //context.ApplicationInstance.Response.Flush();
                //context.Response.End();
                #endregion
                Hashtable hash = new Hashtable();
                hash["error"] = 0;
                hash["message"] = "下载成功！";
                //hash["path"] = zipFilePath + ".zip";
                context.Response.ContentType = "application/octet-stream";
                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                context.Response.Write(JsonMapper.ToJson(hash));
            }
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}